#include <func.h>

int main(void)
{
    char *ip = "192.168.12.129";
    char *port = "8080";

    struct sockaddr_in SockAdd;
    SockAdd.sin_family = AF_INET;
    SockAdd.sin_port = htons(atoi(port));
    SockAdd.sin_addr.s_addr = inet_addr(ip);

    int SockFd = socket(AF_INET,SOCK_STREAM,0);

    connect(SockFd,(struct sockaddr *)&SockAdd,sizeof(SockAdd));

    char buf[60] = {0};
    
    int ret = recv(SockFd,buf,sizeof(buf),0);
    if(ret == 0)
        printf("服务器断开连接！");
    
    printf("收到消息：%s\n",buf);

    // 接收服务器发来的文件
    char Name[60] = {0};
    int len = 0,num = 0;
    int FileLen = 0,PrintLen = 0;

    // 接收文件整体长度
    recv(SockFd,&FileLen,sizeof(off_t),0);

    // 接收文件名
    recv(SockFd,&len,sizeof(int),0);
    printf("len:%d\n",len);
    
    recv(SockFd,Name,len,0);
    printf("Name:%s\n",Name);

    int FileFd = open(Name,O_RDWR | O_CREAT,0666);
    
    printf("----------------------------当前传输进度------------------------------\n");
    
    while(true)
    {
        char File[1000] = {0};
        // 接收文件内容
        recv(SockFd,&num,sizeof(num),0);
        if(num == 0)
        {
            printf("\n文件已接收完毕！\n");
            break;
        }
        
        //if(num != 1000)
        //    printf("num:%d\n",num);

        int ret = 0;
        while(ret < num)
            ret += recv(SockFd,&File[0] + ret,num - ret,0);

        //printf("File:%s\n",File);

        // 保存文件内容
        write(FileFd,File,num);
        
        // 打印进度条
        PrintLen += num;
        double rate = 1.0 * PrintLen / FileLen * 70;
        
        for(int i = 0;i < rate;i++)
            printf(">");    
        
        for(int i = rate; i < 70;i++)
            printf(" ");    

        printf("%.2lf %% \r",rate  * 10 / 7);
    }
    
    close(FileFd);
    close(SockFd);

    return 0;
}






